package com.hanlink.dsp.ca.ui.fragment;

import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import androidx.annotation.RequiresApi;

import com.edge.pbx.view.PbxCircleRadioSeekBar;
import com.edge.pbx.view.PbxCircleSeekBar;
import com.edge.pbx.view.summing.PbxOutputSelectChannelView;
import com.edge.pbx.view.summing.PbxOutputSelectChannelsLayout;
import com.edge.pbxdsp.R;
import com.hanlink.dsp.DspSettings;

import com.hanlink.dsp.ca.model.channel.LevelChannel;
import com.hanlink.dsp.ca.ui.base.BaseAppFragment;
import com.hanlink.dsp.util.DataUtil;
import com.hanlink.dsp.util.ViewUtil;
import com.qztech.utils.YzDebug;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


import static com.hanlink.dsp.DspSettings.ADVANCE_SETTINGS;
import static com.hanlink.dsp.DspSettings.CHANNEL_LENGTH;
import static com.hanlink.dsp.DspSettings.FRENCY_LENGTH;


@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class DelayFragment extends BaseAppFragment implements PbxCircleSeekBar.OnCircleSeekBarFunListener , View.OnClickListener {

    //@BindViews({R.id.pbx_delay_btn_ch1, R.id.pbx_delay_btn_ch2, R.id.pbx_delay_btn_ch3, R.id.pbx_delay_btn_ch4, R.id.pbx_delay_btn_ch5, R.id.pbx_delay_btn_ch6, R.id.pbx_delay_btn_ch7, R.id.pbx_delay_btn_ch8})
    private Button btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8;


    Button[] mBtnDelayValues;
    final int[] mDelayUints = new int[CHANNEL_LENGTH];
    final static boolean[] mCheckeds = new boolean[CHANNEL_LENGTH];
    private static int mLastChannel = 0;
    final List<PbxCircleRadioSeekBar> mDelaySeekBars = new ArrayList<>(CHANNEL_LENGTH);
    PbxOutputSelectChannelsLayout mPbxOutputSelectChannelsLayout;
    final List<PbxOutputSelectChannelView> mChannelViews = new ArrayList<>(CHANNEL_LENGTH);
    @Override
    protected int getResourceId() {
        return R.layout.fragment_delay;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        ViewUtil.initChannelName(rbtnChannels);
        btn1 = findViewById(R.id.pbx_delay_btn_ch1);
        btn2 = findViewById(R.id.pbx_delay_btn_ch2);
        btn3 = findViewById(R.id.pbx_delay_btn_ch3);
        btn4 = findViewById(R.id.pbx_delay_btn_ch4);
        btn5 = findViewById(R.id.pbx_delay_btn_ch5);
        btn6 = findViewById(R.id.pbx_delay_btn_ch6);
        btn7 = findViewById(R.id.pbx_delay_btn_ch7);
        btn8 = findViewById(R.id.pbx_delay_btn_ch8);


        mBtnDelayValues = new Button[]{btn1,btn2,btn3,btn4,btn5,btn6,btn7};

        for(int i = 0;i<mBtnDelayValues.length;i++){
            Button bt = mBtnDelayValues[i];
            bt.setOnClickListener(this);
        }

        mPbxOutputSelectChannelsLayout = findViewById(R.id.pbx_output_selects_layout);
        mDelaySeekBars.clear();
        mDelaySeekBars.add(findViewById(R.id.pbx_delay_seekbar_ch1));
        mDelaySeekBars.add(findViewById(R.id.pbx_delay_seekbar_ch2));
        mDelaySeekBars.add(findViewById(R.id.pbx_delay_seekbar_ch3));
        mDelaySeekBars.add(findViewById(R.id.pbx_delay_seekbar_ch4));
        mDelaySeekBars.add(findViewById(R.id.pbx_delay_seekbar_ch5));
        mDelaySeekBars.add(findViewById(R.id.pbx_delay_seekbar_ch6));
        mDelaySeekBars.add(findViewById(R.id.pbx_delay_seekbar_ch7));
        mDelaySeekBars.add(findViewById(R.id.pbx_delay_seekbar_ch8));
        for (PbxCircleSeekBar bar : mDelaySeekBars) {
            bar.setOnCircleSeekBarListener(mDelayChSeekBarListener);
            bar.setOnCircleSeekBarFunListener(this);
//            bar.setOnCheckedChangeListener(mDelayChSeekBarCheckedListener);
        }
        ViewUtil.findOutputViews(mChannelViews, view, mChannelViewCheckedListener);
    }



    @Override
    public void onResume() {
        super.onResume();
        ViewUtil.initChannelName(mChannelViews);
        ViewUtil.initChannelNames(mDelaySeekBars);
        ViewUtil.initCarType(mPbxOutputSelectChannelsLayout);
        try {
            updateData();
        } catch (Exception ex) {
            YzDebug.d("onResume", ex);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        DataUtil.saveAdvanceSettingsToDb();
        updateOk = false;
    }

    @Override
    public void onRefreshFragment(int cmd) {
        switch (cmd) {
            case CMD_SELECTED:
                updateData();
                break;
        }
    }
    boolean isUpdated = false, updateOk = false;

    private void updateData() {

        updateOk = false;

        ViewUtil.initOutputChannels(DspSettings.SUMMING_SETTINGS,mChannelViews);

        isUpdated = true;

        setCheckedChannel(mLastChannel, true);

        isUpdated = false;
        mRootView.postDelayed(() -> updateOk = true, 200);
    }

    private void setCheckedChannel(int channel, boolean isChecked){
        YzDebug.d("Yang", " setCheckedChannel:" + channel);
        PbxOutputSelectChannelView channelView;
        PbxCircleRadioSeekBar seekBar;
        float[] delays = ADVANCE_SETTINGS.getDelay(); //默认取第一个
        int iDelay = 0;
//        LevelChannel levelChannel = ADVANCE_SETTINGS.getChannelByIndex(channel);
//        if (levelChannel != null)
//            levelChannel.setChecked(isChecked);

        if (channel >= 0 && channel < CHANNEL_LENGTH){
            mCheckeds[channel] = isChecked;
        }

        for(int i = 0, len = mChannelViews.size(); i < len; i++){

            channelView = mChannelViews.get(i);
            channelView.setSelected( mCheckeds[i]);

            seekBar = mDelaySeekBars.get(i);
            seekBar.setEnabled(mCheckeds[i]);
            seekBar.setChecked(mCheckeds[i]);


            iDelay = (int) (delays[i] * 100);
            seekBar.setProgress(iDelay);
            mBtnDelayValues[i].setText(getDelayShowText(i,iDelay));

        }
        mPbxOutputSelectChannelsLayout.postInvalidate();
    }
    private final PbxOutputSelectChannelView.OnCheckChangeListener mChannelViewCheckedListener = (view, isChecked) -> {
        mLastChannel = view.getChannelIndex();
        setCheckedChannel(mLastChannel, true);
    };

    private final PbxCircleSeekBar.OnCircleSeekBarListener mDelayChSeekBarListener = new PbxCircleSeekBar.OnCircleSeekBarListener() {

        @Override
        public void onProgressChange(PbxCircleSeekBar seekBar, int progress, int action) {
            final int index = seekBar.getIndex();
            Log.d("Yang", "onProgressChange :"+ index +"  " + progress +" action:"+ action);
            setChannelDelay(index, progress, action == MotionEvent.ACTION_UP);

        }
    };
    private long mLastSendCmdTime;
    private void setChannelDelay(int index, int delay, boolean sendCmd){
        YzDebug.d("setChannelDelay:"+ index +" " + delay);
        if (index >= 0 && index < mBtnDelayValues.length){
            mBtnDelayValues[index].setText(getDelayShowText(index, delay));
            ADVANCE_SETTINGS.setDelayValue(index,delay/100f);
            final long time = SystemClock.elapsedRealtime();
            if(sendCmd|| (time - mLastSendCmdTime) > 250){
                mLastSendCmdTime = time;
                ADVANCE_SETTINGS.sendTimeDelayCmd(index);
            }
        }
    }
    private String getDelayShowText(int index,int v){
        float fv = v/100f;
        switch (mDelayUints[index]) {
            case 1:
                return String.format("%dcm",(int) (fv * 34) );
            case 2:
                return String.format("%din",(int) (fv * 34 * 0.39));

            default:
//                return  fv +"ms";
                return String.format("%.02fms",fv);
        }
    }
//    @OnClick({R.id.pbx_delay_btn_ch1, R.id.pbx_delay_btn_ch2, R.id.pbx_delay_btn_ch3, R.id.pbx_delay_btn_ch4, R.id.pbx_delay_btn_ch5, R.id.pbx_delay_btn_ch6, R.id.pbx_delay_btn_ch7, R.id.pbx_delay_btn_ch8})
//    public void onBthChClick(View view) {
//        int index = -1;
//        switch (view.getId()) {
//            case R.id.pbx_delay_btn_ch1:
//                index = 0;
//                break;
//            case R.id.pbx_delay_btn_ch2:
//                index = 1;
//                break;
//            case R.id.pbx_delay_btn_ch3:
//                index = 2;
//                break;
//            case R.id.pbx_delay_btn_ch4:
//                index = 3;
//                break;
//            case R.id.pbx_delay_btn_ch5:
//                index = 4;
//                break;
//            case R.id.pbx_delay_btn_ch6:
//                index = 5;
//                break;
//            case R.id.pbx_delay_btn_ch7:
//                index = 6;
//                break;
//            case R.id.pbx_delay_btn_ch8:
//                index = 7;
//                break;
//        }
//        if (index == -1)return;
////        mLastChannel = index;
////        setCheckedChannel(mLastChannel);
//        int unit = (mDelayUints[index] + 1)%3;
//        mDelayUints[index] = unit;
//        ((Button)view).setText(getDelayShowText(index, mDelaySeekBars.get(index).getProgress()));
//
//    }

    @Override
    public void onFunClick(PbxCircleSeekBar bar,PbxCircleSeekBar.FunId id) {
        int index = bar.getIndex();
        YzDebug.d("onFunClick:" + index +"  " + id);
        switch (id){
            case FUN_ID_TITLE:
                setCheckedChannel(index, !mCheckeds[bar.getIndex()]);
                break;
            case FUN_ID_ADD:
                int v1 = (int) (ADVANCE_SETTINGS.getDelayValue(index)*100);
                YzDebug.d("onFunClick v1:" + v1 +" " + Arrays.toString(ADVANCE_SETTINGS.getDelay()));
                if(v1 < DspSettings.MAX_TIME_DELAY){
                    v1 += 2;
                    if (v1 > DspSettings.MAX_TIME_DELAY)
                        v1 = DspSettings.MAX_TIME_DELAY;
                    setChannelDelay(index, (int)v1, false);
                }
                break;
            case FUN_ID_SUB:
                v1 = (int) (ADVANCE_SETTINGS.getDelayValue(index)*100);
                if(v1 > 0){
                    v1 -= 2;
                    if (v1 < 0)v1 = 0;
                    setChannelDelay(index, (int) v1, false);
                }
                break;
        }

    }

    @Override
    public void onClick(View view) {
        int index = -1;
        switch (view.getId()) {
            case R.id.pbx_delay_btn_ch1:
                index = 0;
                break;
            case R.id.pbx_delay_btn_ch2:
                index = 1;
                break;
            case R.id.pbx_delay_btn_ch3:
                index = 2;
                break;
            case R.id.pbx_delay_btn_ch4:
                index = 3;
                break;
            case R.id.pbx_delay_btn_ch5:
                index = 4;
                break;
            case R.id.pbx_delay_btn_ch6:
                index = 5;
                break;
            case R.id.pbx_delay_btn_ch7:
                index = 6;
                break;
            case R.id.pbx_delay_btn_ch8:
                index = 7;
                break;
        }
        if (index == -1)return;
//        mLastChannel = index;
//        setCheckedChannel(mLastChannel);
        int unit = (mDelayUints[index] + 1)%3;
        mDelayUints[index] = unit;
        ((Button)view).setText(getDelayShowText(index, mDelaySeekBars.get(index).getProgress()));

    }
}
